package com.miracle.java2110.controller;

import com.miracle.java2110.QinuiUtils;
import com.miracle.java2110.common.PageVo;
import com.miracle.java2110.common.R;
import com.miracle.java2110.pojo.Drinks;
import com.miracle.java2110.service.DrinksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author rwg
 */
@RestController
@RequestMapping("/drinks")
@CrossOrigin("*")  // 允许所有域发送请求
public class DrinksController {
    @Autowired
    private DrinksService drinksService;

    @RequestMapping("/list")
    public List<Drinks> findDrinks() {

        return drinksService.findDrinks();
    }

    @RequestMapping("/pageData")
    public PageVo<Drinks> getPageData(@RequestParam Map<String, Object> params) {

        return drinksService.getPageData(params);
    }

    @RequestMapping("/delete")
    public R deleteById(Integer did) {
        return drinksService.deleteById(did);
    }

    @RequestMapping("/update")
    public R updateById(Drinks drinks) {
        return drinksService.updateById(drinks);
    }

    @RequestMapping("/add")
    public R addUser(Drinks drinks) {
        return drinksService.addUser(drinks);
    }

    // 文件上传
    @RequestMapping("/upload")
    public R uploadPic(MultipartFile file, HttpServletRequest request) throws IOException {
        // 上传到本地 实际开发不用这种方式
        // return uploadLoacl(file, request);

        String filename = file.getOriginalFilename();

        // 得到文件后缀名
        String suffix = filename.substring(filename.lastIndexOf("."));

        String fileName = UUID.randomUUID().toString() + suffix;

        byte[] bytes = file.getBytes();

        QinuiUtils.uploadBytes2Qiniu(bytes, fileName);


        return R.ok(200, "上传成功", "http://r23iu742u.hd-bkt.clouddn.com/" + fileName);

    }

}
